package Controller;

import Model.QuyuAlarm;
import Model.SysInfo;
import Dao.UserDao;
import Model.User;
import Model.UserQuery;
import Model.GeneralUser;
import Model.permission.Permission;
import Service.QuyuAlarmService;
import Service.RoleService;
import Service.SysInfoService;
import Service.UserService;
import utils.ResponseBody.JsonResponse;
import utils.ResponseBody.ResponseStatus;
import utils.ReturnData;
import utils.ReturnDataForLayui;
import utils.pages.Page;
import Model.permission.ResponseResult;
import org.springframework.ui.Model;
import utils.pages.PageBean;
import utils.permission.ConstantsUtils;
import utils.permission.IStatusMessage.SystemStatus;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import utils.permission.PageDataResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.annotation.Resource;
import javax.swing.*;
import java.util.*;


//
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    UserService userService;
    @Resource
    SysInfoService sysInfoService;//实例化一个service
    @Resource
    QuyuAlarmService quyuAlarmService;
    @Autowired
    UserDao userDao;

    @Resource
    private RoleService roleService;

    private final int PAGE_MAX_NUM = 16; //面页最大记录数

//    private static final Logger logger = LoggerFactory.getLogger(JGBKController.class);
//
//    @Resource
//    private JGBKService jgbkService;


    private void formatPagination(UserQuery query){
        //分页格式化
        int page = query.getPage();
        int size = query.getSize();
        if(page > 0 && size > 0){
            size = size > PAGE_MAX_NUM ? PAGE_MAX_NUM: size;
            int start = (page - 1) * size;
            start = start<0?0:start;
            query.addPagination(start, size);
        }
    }

    /**
     * 用户列表
     *
     * @return ok/fail
     */
    @RequestMapping(value = "/getUserPage", method = RequestMethod.GET)
    @ResponseBody
    public Page<User> getUserPage() {
        logger.debug("列表！");
        Page<User> UserPage = null;
        try {
            UserPage = userService.Show_All_User();
            logger.debug("列表查询=UserPage:" + UserPage);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("角色查询异常！", e);
        }
        System.out.println("AAAAAAAAAA" + UserPage);
        return UserPage;
    }
    /**
     * 用户登陆
     *
     * @param user
     * @param session
     * @param rememberMe
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult login (
            User user,
            HttpSession session,
            @RequestParam(value = "rememberMe", required = false) boolean rememberMe)
    {
        System.out.println("进入contoller层");
        logger.debug("用户登录，请求参数=user:" + user + "，是否记住我：" + rememberMe);
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(SystemStatus.ERROR.getCode()); //先赋值请求失败:1001
        System.out.println("用户登录1"+user);

        //如果前端传过来的user为空
        if (null == user) {
            System.out.println("输入用户空");
            responseResult.setCode(SystemStatus.PARAM_ERROR.getCode());//请求参数有误：1002
            responseResult.setMessage("请求参数有误，请您稍后再试");
            logger.debug("用户登录，结果=responseResult:" + responseResult);
            System.out.println("用户登录2");
            return responseResult;
        }
//        System.out.println(validatorRequestParam(user, responseResult));

        //参数有误，直接返回
        if (!validatorRequestParam(user, responseResult)) {
            logger.debug("用户登录，结果=responseResult:" + responseResult);
            System.out.println("用户登录3");
            return responseResult;
        }

        user.setPassword(DigestUtils.md5Hex(user.getPassword()));//密码md5码加密
//        System.out.println(user.getPassword());

        //检查用户是否存在
        System.out.println("用户登录11111");
        System.out.println("User_number:"+user.getUser_number());
        User existUser = this.userService.findUserByName(user.getUser_number());
        System.out.println("用户登录22222"+existUser);
        System.out.println(existUser);
        if (existUser == null) {
            System.out.println("该用户不存在");
            responseResult.setMessage("该用户不存在，请您联系管理员");
            responseResult.setCode(SystemStatus.USER_NULL.getCode()); //用户不存在:1004

            logger.debug("用户登录，结果=responseResult:" + responseResult);
            System.out.println("用户登录4");
            return responseResult;
        }

        //验证用户状态
        if(existUser.getStatus() == 2){
            responseResult.setMessage("该用户已经被冻结");
            responseResult.setCode(SystemStatus.LOCK.getCode());
            return responseResult;
        }else if(existUser.getStatus() == 3){
            responseResult.setMessage("该用户未注册");
            responseResult.setCode(SystemStatus.USER_NULL.getCode());
            return responseResult;
        }

        //检查用户登陆密码是否正确
        existUser = this.userService.findUser(user);
        if (existUser == null) {
            responseResult.setMessage("输入密码错误");
            responseResult.setCode(SystemStatus.PASSWORD_ERROR.getCode()); //密码错误：1005

            logger.debug("用户登录，结果=responseResult:" + responseResult);
            System.out.println("用户登录5");
            return responseResult;
        }
//        在检查用户后调用
//          System.out.println(existUser.toString());
//          this.sysInfoService.insert(existUser);//调用函数

        //获取用户权限列表
        try {
            List<Permission> allPermissions;
            if(existUser.getRole_id() == 0){
                allPermissions = roleService.findPerms();
            }else{
                allPermissions = roleService.getUserPerms(existUser.getUser_id());
            }
            if(allPermissions == null){
                throw new RuntimeException("无效的用户权限");
            }
            //移除路劲为/的权限，根路劲不拦截
            existUser.setPermissions(GeneralUser.UserUtil.getNoneRootPermissions(allPermissions));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据用户id查询权限树列表查询异常！", e);
            responseResult.setMessage("读取权限失败");
            responseResult.setCode(SystemStatus.ERROR.getCode());
            return responseResult;
        }

        session.setAttribute(ConstantsUtils.SessionObj.CURRENT_USER, existUser);
        System.out.println(session.getAttribute(ConstantsUtils.SessionObj.CURRENT_USER));
        System.out.println("根据用户名密码进行登陆");
        //根据用户名密码进行登陆
        responseResult.setCode(SystemStatus.SUCCESS.getCode());
        responseResult.setMessage(SystemStatus.SUCCESS.getMessage());  //这里换一下，存放user_message字段，1 2 3 4 5...9代表年级，null代表非学生角色
        responseResult.setMessage(existUser.getUser_role());
//        responseResult.setUser_id(existUser.getUser_id());
        responseResult.setUser_number(existUser.getUser_number());
//        responseResult.setDepartment_settlement_code(existUser.getDepartment_settlement_code());

        System.out.println(responseResult);
        return responseResult;
    }



    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult signup (User user)
    {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(SystemStatus.ERROR.getCode()); //先赋值请求失败:1001
        System.out.println("用户注册"+user);

        //如果前端传过来的user为空
        if (null == user) {
            System.out.println("输入用户空");
            responseResult.setCode(SystemStatus.PARAM_ERROR.getCode());//请求参数有误：1002
            responseResult.setMessage("请求参数有误，请您稍后再试");
            return responseResult;
        }

        //参数有误，直接返回
        if (!validatorRequestParam(user, responseResult)) {
            logger.debug("注册登录，结果=responseResult:" + responseResult);
            return responseResult;
        }

        //检查用户是否存在
        User existUser = this.userService.findUserByName(user.getUser_number());

        if (existUser == null) {
            System.out.println("该用户不存在");
            responseResult.setMessage("该用户不存在，请您联系管理员");
            responseResult.setCode(SystemStatus.USER_NULL.getCode()); //用户不存在:1004
            return responseResult;
        }
        System.out.println("存在用户"+existUser);

        if(existUser.getStatus() != 3){
            System.out.println("该用户已经注册");
            responseResult.setMessage("该用户已经注册");
            return responseResult;
        }

        String str;
        //检查信息正确
        str = existUser.getIdentity();
        if(str == null || !str.equals(user.getIdentity())){
            responseResult.setMessage("身份证不匹配");
            logger.debug("注册失败" + responseResult);
            return responseResult;
        }
        str = existUser.getUser_mobile();
        if(str == null || !str.equals(user.getUser_mobile())){
            responseResult.setMessage("电话号码不匹配");
            logger.debug("注册失败" + responseResult);
            return responseResult;
        }

        //注册
        User signupUser = new User();
        signupUser.setUser_id(existUser.getUser_id());
        signupUser.setStatus(1);
        signupUser.setUpdate_time(new Date());
        signupUser.setPassword(DigestUtils.md5Hex(user.getPassword()));//密码md5码加密);
        System.out.println("注册用户"+signupUser);
        if(! userService.update(signupUser)){
            responseResult.setMessage("注册失败");
            return responseResult;
        }

        responseResult.setCode(SystemStatus.SUCCESS.getCode());
        responseResult.setMessage(SystemStatus.SUCCESS.getMessage());

        System.out.println(responseResult);
        return responseResult;
    }

    /**
     * 校验请求参数
     *
     * @param obj
     * @param response
     * @return
     */
    protected boolean validatorRequestParam (Object obj, ResponseResult response) {
        boolean flag = false;
        Validator validator = new Validator();
        List<ConstraintViolation> ret = validator.validate(obj);
        System.out.println("obj:"+obj);
        System.out.println("ret:"+ret);
        System.out.println("flag:"+ret.size());
        if (ret.size() > 0) {
            response.setCode(SystemStatus.PARAM_ERROR.getCode());
            response.setMessage(ret.get(0).getMessageTemplate());
        } else {
            flag = true;
            // 校验参数有误09809op;.cv
        }
        return flag;
    }

    @RequestMapping("/test")
    public String test(Model model, int id) {
        System.out.println("欢迎进入后台管理");
        // 根据id查询案例
        System.out.println("id:"+id);
        User user = this.userDao.findUserById(id);
        model.addAttribute("user",user);
        System.out.println("user:"+user);
        return "forward:/index.jsp";
    }


//    在此添加弹框
    /**
     *进入主页
     * @param session
     * @return
     */
    @RequestMapping("/index")
    public String toIndex(Model model, HttpSession session) {

        // 根据id查询案例
        User onlineUser = (User)session.getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        if(null == onlineUser){
            return "forward:/login.jsp";
        }
        model.addAttribute("user",onlineUser);
        System.out.println("Welcome");
        System.out.println("user:"+onlineUser);
        /*
        String user_id = null;
        user_id = onlineUser.getUser_number();
        List<SysInfo> getLogTime = sysInfoService.getLogTime(user_id);
        System.out.println("user_id"+user_id);
        List<QuyuAlarm> getAllAlarmListShow = quyuAlarmService.getAllAlarmListShow();
        int a = 0;
        a = onlineUser.getRole_id();
        if(a == 1 || a == 0){
            System.out.println("当前用户为管理员，弹出消息框");
//            判断上次登录时间<异常时间<当前登录时间
            Date yichang = getAllAlarmListShow.get(0).getInsert_time();
            Date shangciLog = getLogTime.get(1).getOperTime();
            Date dangqianLog = getLogTime.get(0).getOperTime();
            System.out.println("getLastAlarmListShow为"+getAllAlarmListShow.get(0).getInsert_time());
            System.out.println("getLogTime分别为"+getLogTime.get(0).getOperTime()+","+getLogTime.get(1).getOperTime());
            if (shangciLog.getTime() <= yichang.getTime() && yichang.getTime()<=dangqianLog.getTime()) {
                System.out.println("当前用户为管理员且有异常消息，弹出消息框");
                model.addAttribute("flag", 1);
            }

        }*/
        return "forward:/index.jsp";
    }

    /**
     * 开始更改
     * @param
     * @return
     */
    @RequestMapping("/listPage")
    public String listPage(){
        return "YiBaoMonitor/SysMonitor/User";
    }

    @RequestMapping("/getList")
    @ResponseBody
    public JsonResponse getList(UserQuery query){
        JsonResponse res = new JsonResponse(ResponseStatus.SUCCESS);
        formatPagination(query);
        PageBean<User> page = userService.getList(query);
        res.setData(page);
        return res;
    }

    @RequestMapping("/getName")
    @ResponseBody
    public ReturnDataForLayui getName(User user){
        return userService.getName(user);
    }

    @RequestMapping("/addPage")
    public String addPage(){
        return "YiBaoMonitor/SysMonitor/add_User";
    }

    @RequestMapping("/add")
    @ResponseBody
    public ReturnData add(User user){
        user.setStatus(3);
        return userService.add(user);
    }

    @RequestMapping("/editPage")
    public String editPage(){
        return "YiBaoMonitor/SysMonitor/edit_User";
    }

    @RequestMapping("/update")
    @ResponseBody
    public JsonResponse update(User user){
        JsonResponse res = new JsonResponse(ResponseStatus.SUCCESS);
        if(user.getPassword() != null && user.getPassword().length() >0){
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));//密码md5码加密
        }
        if(! userService.update(user)){
            res.set(ResponseStatus.ERROR, "更新错误");
        }
        return res;
    }

    @RequestMapping("/updateState")
    @ResponseBody
    public ReturnData updateState(User user){
        return userService.updateState(user);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ReturnData delete(User user){
        return userService.delete(user);
    }





    @RequestMapping(value = "/setuser", method = RequestMethod.POST,  produces={"text/plain;charset=UTF-8"} )
    @ResponseBody
    public String setuser(User user, HttpSession session) {
        logger.debug("设置用户[新增或更新]！user:" + user );
        try {
            //两个前端数据的验证
            if (null == user) {
                logger.debug("请您填写用户信息");
                return "请您填写用户信息";
            }

            // 设置用户[新增或更新]
            logger.info("设置用户[新增或更新]成功！user=" + user );
            return userService.setuser(user,  session);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置用户[新增或更新]异常！", e);
            return "操作异常，请您稍后再试";
        }
    }

    @RequestMapping(value = "/getusers", method = RequestMethod.POST)
    @ResponseBody
    public PageDataResult getuser(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            User userSearch
    ) {
        PageDataResult pdr = new PageDataResult();
        try {
            if (null == page) {
                page = 1;
            }
            if (null == limit) {
                limit = 10;
            }
            pdr = userService.getusers(userSearch, page, limit);
            logger.debug("用户列表查询=pdr:" + pdr);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户列表查询异常！", e);
        }

        return pdr;
    }

    @RequestMapping(value = "/getuser", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getuser(@RequestParam("user_id") Integer id) {
        logger.debug("查询用户数据！userId:" + id);
        Map<String, Object> map = new HashMap<>();
        try {
            if (null == id) {
                logger.debug("请求参数有误，请您稍后再试");
                map.put("msg", "请求参数有误，请您稍后再试");
                return map;
            }
            // 查询用户
            User user = userService.getuser(id);
            logger.debug("查询用户数据！user=" + user);
            if (null != user) {
                map.put("user", user);
                map.put("msg", "ok");
            } else {
                map.put("msg", "查询信息有误，请您稍后再试");
            }
            logger.debug("查询成功！map=" + map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "查询用户错误，请您稍后再试");
            logger.error("查询用户数据异常！", e);
        }
        return map;
    }

    @RequestMapping(value = "/deluser", method = RequestMethod.POST, produces={"text/plain;charset=UTF-8"})
    @ResponseBody
    public String deluser(
            @RequestParam("user_id") Integer id,
            HttpSession session
    ) {
        logger.debug("删除用户！id:" + id);
        String msg = "";
        try {
            if (null == id ) {
                logger.debug("删除用户，结果=请求参数有误，请您稍后再试");
                return "请求参数有误，请您稍后再试";
            }
            // 删除用户
            msg = userService.deluser(id);
            logger.info("删除用户:" + msg + "！userId=" + id );
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除用户异常！", e);
            msg = "操作异常，请您稍后再试";
        }
        return msg;
    }

    /**
     *
     * 跳转到个人信息界面
     */
    @RequestMapping(value = "/toPersonal")
    public String toPersonal(Model model,HttpServletRequest request){
        System.out.println("进入controller层");
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        System.out.println("controller层：user信息:" + user);
        model.addAttribute("user",user);
        return "/YiBaoMonitor/SysMonitor/personal";
    }

    /**
     *
     * 修改个人信息
     */
    @RequestMapping(value = "/editPersonal")
    public String editPersonal(Model model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        System.out.println("controller层：user信息:" + user);
        model.addAttribute("user",user);
        return "/YiBaoMonitor/SysMonitor/PersonalInfo";
    }

}
